//
//  SubscribeViewController.swift
//  NDAi
//
//  Created by 丸子 on 2024/6/20.
//

import UIKit
import YYText

class SubscribeViewController: BaseViewController {
    var headerView = SubscribeHeaderView()
    var service:SubscribeService?
    var dataSource:[ProductModel] = []
    var type:Int = 0
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = true
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.navigationBar.isHidden = false
    }
    private lazy var backBtn: XFButton = {
        let button = XFButton(type: .custom)
        button.setImage(UIImage(named: "icon_video_back"), for: .normal)
        return button
    }()
    
    lazy var agBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.imageForNormal = UIImage(named: "icon_vip_nor")
        button.imageForSelected = UIImage(named: "icon_subscribe_sel")
        button.isSelected = true
        return button
    }()
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.rowHeight = UITableView.automaticDimension
        tableView.register(cellWithClass: SubscribeQYCell.self)
        tableView.register(cellWithClass: SubscribeGoodsCell.self)
        tableView.register(cellWithClass: SubscribePayCell.self)
        tableView.register(cellWithClass: SubscribeUserCell.self)
        tableView.register(cellWithClass: SubscribeHeaderCell.self)
        tableView.separatorStyle = .none
        tableView.backgroundColor = .clear
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 68, right: 0)
        return tableView
    }()
    
    private lazy var buyBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.titleForNormal = "立即解锁"
        button.titleFont = UIFont.pingFangSCRegular(ofSize: 16)
        button.titleColorForNormal = Theme.color.text_d1
        button.allRound(24)
        return button
    }()
    
    private lazy var mailLb: UILabel = {
       let label = UILabel()
        label.textColor = .white
        label.font = UIFont.pingFangSCRegular(ofSize: 13)
        label.text = "客服邮箱: service@letonglive.com"
        label.isHidden = true
        return label
    }()
    
    
    private lazy var restoreBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.setTitle("恢复购买", for: .normal)
        button.titleColorForNormal = UIColor(hexString: "#CCCCCC")
        button.titleLabel?.font = UIFont.pingFangSCRegular(ofSize: 12)
        button.isHidden = true
        return button
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor(hexString: "#28272D")
        self.view.addSubview(self.tableView)
        self.view.addSubview(buyBtn)
        self.view.addSubview(backBtn)
        self.view.addSubview(restoreBtn)
        self.view.addSubview(mailLb)
        self.navigationItem.title = "订阅"
        self.tableView.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.leading.trailing.equalToSuperview()
            make.bottom.equalTo(self.safeBottom)
        }
        buyBtn.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview().inset(14)
            make.bottom.equalTo(self.safeBottom).offset(-16)
            make.height.equalTo(48)
        }
        backBtn.snp.makeConstraints { make in
            make.top.equalTo(self.safeTop).offset(10)
            make.leading.equalToSuperview().offset(14)
            make.width.height.equalTo(24)
        }
        restoreBtn.snp.makeConstraints { make in
            make.centerY.equalTo(backBtn)
            make.trailing.equalToSuperview().offset(-14)
        }
        buyBtn.themeGradient([UIColor(hexString: "#FFF5E6"), UIColor(hexString: "#DEAA62")], .leftToRight)
        self.tableView.tableHeaderView = self.headerView
        
        backBtn.setClosureTouchUpInside_k { [weak self] in
            self?.clickRet()
        }
        
        buyBtn.setClosureTouchUpInside_k { [weak self] in
            self?.clickSubscribe()
        }
        
        mailLb.snp.makeConstraints { make in
            make.bottom.equalTo(self.safeBottom).offset(-10)
            make.centerX.equalToSuperview()
        }
//        restoreBtn.setClosureTouchUpInside_k { [weak self] in
//            guard let self = self else { return }
//            self.service.resetVerifyCountForPaymentTransactionInfos()
//        }
        agBtn.setClosureTouchUpInside_k { [weak self] in
            guard let self = self else { return }
            self.agBtn.isSelected = !self.agBtn.isSelected
        }
        requestGoods()
        self.bindEvent()
    }
    func bindEvent(){
        self.service = SubscribeService.shared
        self.service?.PaySuccessBlock = { orderId in
            NDProgressHUD.showSuccess(title: "", subtitle: "购买成功")
        }
        self.service?.payBlock = {[weak self] type, msg, code in
            XLog.d("支付回调 type", "\(type) \(msg)")
            guard let self = self else { return }
            if type == 0 {
//                NDProgressHUD.show(message: msg)
                NDProgressHUD.showLoadingText(msg)
            }else if type == -1 {
                if msg.count > 0 {
                    NDProgressHUD.showError(title: "", subtitle: msg)
                }else {
                    NDProgressHUD.hide()
                }
            }else if type == 1{
                self.tableView.reloadData()
                NDProgressHUD.show(message: msg)
            }else if type == -2 {
                NDProgressHUD.show(message: msg)
            }else {
                NDProgressHUD.hide()
            }
        }
    }
    
    func requestGoods(){
        if let a = Appearance.shared.accoutModel?.userOtherInfo?.vip_end_time?.checkVIPExpiryDate(), !a {
            buyBtn.isHidden = true
            mailLb.isHidden = false
            return
        }
        mailLb.isHidden = true
        NDProgressHUD.showLoading()
        RequestService.instance.vipProduct { models in
            NDProgressHUD.hide()
            self.dataSource = models
            self.tableView.reloadData()
        } failureClosure: { error in
            NDProgressHUD.hide()
        }
    }
    
    func clickSubscribe(){
        if !self.agBtn.isSelected {
            NDProgressHUD.show(message: "请先同意会员服务协议")
            return
        }
        if let model = self.dataSource.first(where: { $0.isSelect }) {
            NDProgressHUD.showLoading()
            let productIds = self.dataSource.compactMap { $0.apple_product_id ?? "" }
            self.service?.buyProducts(productId: model.apple_product_id ?? "", allProductIds: productIds)
        }
    }
    
    
    func clickRet() {
        if type == 1 {
            let view = HomeTwoTopupPOPView()
            Appearance.addViewToWindow(view)
            view.chooseClose = { [weak self] in
                self?.popSelf(animation: true)
            }
        }else {
            self.popSelf(animation: true)
        }
    }
}

extension SubscribeViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        3
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0  {
            if let isVip = Appearance.shared.accoutModel?.userOtherInfo?.is_vip, isVip == 1 {
                return 1
            }else {
                return 0
            }
        }else if section == 1 {
            return 2
        }else {
            return dataSource.count
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withClass: SubscribeUserCell.self)
            cell.setup()
            return cell
        } else if indexPath.section == 1 {
            if indexPath.row == 0 {
                let cell = tableView.dequeueReusableCell(withClass: SubscribeHeaderCell.self)
                return cell
            }
            let cell = tableView.dequeueReusableCell(withClass: SubscribeQYCell.self, for: indexPath)
            return cell
        }else {
            let model = dataSource[indexPath.item]
            let cell = tableView.dequeueReusableCell(withClass: SubscribeGoodsCell.self, for: indexPath)
            cell.timeLb.text = model.name ?? ""
            cell.moneyLb.text = "¥\(model.price ?? 0)"
            cell.leftLb.text = "  \(model.price_by_days ?? 0)元/天  "
            cell.createAttributedText(money: "\(model.donate_days ?? 0)")
            cell.lastMoneyLb.text = "¥ \(model.price_old ?? 0)"
            if model.isSelect {
                cell.timeLb.textColor = UIColor(hexString: "#823B1A")
                cell.moneyLb.textColor = UIColor(hexString: "#823B1A")
                //                cell.leftLb.backgroundColor = UIColor(hexString: "#FFB056")
                cell.leftLb.backgroundColor = UIColor(hexString: "#5B5F71")
                cell.sendLb.layer.borderWidth = 1
                cell.sendLb.layer.borderColor = UIColor(hexString: "#823B1A").cgColor
                cell.sendLb.textColor = UIColor(hexString: "#823B1A")
            }else {
                cell.timeLb.textColor = .white
                cell.moneyLb.textColor = .white
                cell.leftLb.backgroundColor = UIColor(hexString: "#5B5F71")
                cell.sendLb.layer.borderColor = UIColor(hexString: "#BABABA").cgColor
                cell.sendLb.layer.borderWidth = 1
                cell.sendLb.textColor = .white
            }
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if indexPath.section == 2 {
            let model = dataSource[indexPath.item]
            if let myCell = cell as? SubscribeGoodsCell {
                if model.isSelect {
                    myCell.backView.themeGradient([UIColor(hexString: "#FFF5E6"), UIColor(hexString: "#DEAA62")], .leftToRight)
                }else {
                    myCell.backView.themeGradient([UIColor(hexString: "#8F8F92"), UIColor(hexString: "#6B6A6C")], .leftToRight)
                }
            }
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 2 {
            for i in 0..<self.dataSource.count {
                self.dataSource[i].isSelect = false
            }
            dataSource[indexPath.item].isSelect = true
            self.tableView.reloadData()
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        if section == 2 && self.dataSource.count > 0{
            let view = UIView()
            view.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 50)
            view.addSubview(agBtn)
            agBtn.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(18)
                make.top.equalToSuperview().offset(14)
                make.width.height.equalTo(24)
            }
            let label = YYLabel()
            let fullText = "开通即同意《会员服务协议》"
            let attributedString = NSMutableAttributedString(string: fullText)
            let fullRange = NSRange(location: 0, length: attributedString.length)
            attributedString.addAttributes([
                .font: UIFont.pingFangSCRegular(ofSize: 12), // 替换成你需要的字体
                .foregroundColor: UIColor.white // 替换成你需要的颜色
            ], range: fullRange)
            // 设置《用户协议》的链接和颜色
            let userAgreementRange = (fullText as NSString).range(of: "《会员服务协议》")
            attributedString.yy_setTextHighlight(userAgreementRange, color: UIColor(hexString: "#45FFFF"), backgroundColor: nil) { _, _, _, _ in
                if let url = URL(string: "\(apiHost)/api/text/authorization") {
                    UIApplication.shared.open(url)
                }
            }
            label.attributedText = attributedString
            view.addSubview(label)
            label.snp.makeConstraints { make in
                make.centerY.equalTo(agBtn)
                make.leading.equalTo(agBtn.snp.trailing).offset(4)
            }
            return view
        }else {
            return UIView()
        }
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == 2  && self.dataSource.count > 0{
            return 50
        }
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
}
